/* eslint-disable max-len */
/* eslint-disable no-multiple-empty-lines */
/* eslint-disable prettier/prettier */

import React, { PureComponent, useState} from 'react';
import { View, StyleSheet, Text, TouchableOpacity, Alert, Image, Dimensions } from "react-native";
import { connect } from 'react-redux';
import { Divider, Utils, TYListItem, IconFont, Slider, BrickButton, TYText, Dialog, Toast, TopBar } from "tuya-panel-kit";
import { HueSaturationPicker } from '@tuya/tuya-panel-lamp-sdk';
import Res from '../../res';
import { debounce } from '../../utils';
import TYSdk from '../../api';
import dpCodes from '../../config/dpCodes';
import Strings from "../../i18n";
import { strlen } from "../../utils";
import { count } from 'rxjs-compat/operator/count';
import kColor from "../../config/kColor";




const { convertX: cx } = Utils.RatioUtils;
const { convertY: cy, viewWidth, viewHeight } = Utils.RatioUtils;
const { hsvToRgb } = Utils.ColorUtils;
const TYEvent = TYSdk.event;
const TYDevice = TYSdk.device;
const TYNative = TYSdk.native;
const TYMobile = TYSdk.mobile;
const textStyle = {
  height: 64,
  color: '#333',
  justifyContent: 'center',
  alignItems: 'center',
  textAlign: 'center',
  backgroundColor: '#fff',
};

const {
  light_edit_on: light_edit_onCode,
  light_edit_color: light_edit_colorCode,
  light_edit_bright: light_edit_brightCode,
  light_mode_list: light_mode_listCode,
} = dpCodes;



class CustomLightScene extends PureComponent {
  constructor(props) {
    super(props);
    const { light_edit_bright, listdata, listitem } = this.props;
    console.log('listitem', listitem);
    console.log('listdata', listdata);
    this.state = {
      lightSet: listitem ? listitem.lightSet : light_edit_bright,
      listItem: listitem,
      listData: listdata,
      customName: listitem ? listitem.title : '',
      modeRGB: listitem ? listitem.modeRGB : '',
      color: listitem ? listitem.color : '',
      showToast: false,
      toastTips: '',
    };
    this.flage = false;



  }

  componentDidMount() {
    const { light_edit_on } = this.props;

    if (!light_edit_on) {
      TYDevice.putDeviceData({
        [light_edit_onCode]: true,
      });
    }

    // const h = 300;
    // const s = 50;
    // const v = this.state.lightSet;
    // console.log(h);
    // console.log(s);
    // console.log(v);
    // const rgb = hsvToRgb( h, s, v );
    // console.log(rgb);
    // const red = this.numberToHex2(rgb['r']);
    // const green = this.numberToHex2(rgb['g']);
    // const blue = this.numberToHex2(rgb['b']);
    // const rgbHex = red + green + blue;
    // const rgbDec = this.hexToDec(rgbHex);
    // this.sliderColor(rgbDec);
    // this.setState({ modeRGB: rgbDec.toString() });

  }

  componentWillUnmount(){
    TYDevice.putDeviceData({
      [light_edit_onCode]: false,
    });
  }

  setValue = (newValue) => {
    this.setState({ customName: newValue });
    console.log(newValue);
  };

  setLight = (newValue) => {
    this.setState({ lightSet: newValue });
    console.log(newValue);
  };

  numberToHex2(num) {
    let hex = num.toString(16);
    return hex.padStart(2, '0');
  }

  hexToDec(hexString) {
    return parseInt(hexString, 16);
  }

  sliderClicked = debounce(v => {
    console.log('灯光亮度', v);
    TYDevice.putDeviceData({
      [light_edit_brightCode]: v,
    });
  });

  sliderColor = debounce(v => {
    console.log('灯光颜色', v);
    TYDevice.putDeviceData({
      [light_edit_colorCode]: v,
    });
  });

  addClick() {
    if (this.state.customName) {
      const { listData } = this.state;
      const { light_mode_list } = this.props;
      let modeId = '';
      let modeIds = ['6','8','9','10','11']
      // 删除数组a中与数组b中相同的元素
      const filteredArray = modeIds.filter(item => !listData.includes(item));

      console.log('filteredArray', filteredArray);
      modeId = filteredArray[0]
      console.log('modeId',modeId);

      const newModeString = this.state.modeRGB + '-' + this.state.customName + '-' + modeId + '-' + this.state.lightSet ;
      console.log(newModeString);
      const setModeString = light_mode_list + ',' + newModeString;
      const list = TYSdk.getLightModeList();

      TYDevice.putDeviceData({
        [light_mode_listCode]: setModeString,
      });

      this.setState({showToast: true, toastTips: Strings.saved_successfully});

      TYSdk.Navigator.pop();

    } else {

      this.setState({showToast: true, toastTips: Strings.light_mode_name_placeholder});

    }

  };

  editClick() {
    if (this.state.customName) {
      const { listItem } = this.state;
      const { light_mode_list } = this.props;
   
      modeId = listItem.key
      console.log('modeId',modeId);

      const newModeString = this.state.modeRGB + '-' + this.state.customName + '-' + modeId + '-' + this.state.lightSet ;
      console.log(newModeString);
      let arrList = light_mode_list.split(",");
      const index = arrList.indexOf(listItem.string);
      if (index >= 0 && index < arrList.length) {
        arrList[index] = newModeString;
      }
      
      const setModeString = arrList.toString();
      //const list = TYSdk.getLightModeList();

      TYDevice.putDeviceData({
        [light_mode_listCode]: setModeString,
      });

      this.setState({showToast: true, toastTips: Strings.saved_successfully});

      TYSdk.Navigator.pop();

      // Dialog.alert({
      //   title: '添加成功',
      //   subTitle: '已成功添加灯光模式',
      //   confirmText: '确认',
      //   onConfirm: (data, { close }) => {
      //     TYSdk.Navigator.pop();
      //     close();
      //   },
      // });
    } else {

      this.setState({showToast: true, toastTips: Strings.light_mode_name_placeholder});

      // Dialog.alert({
      //   title: '添加失败',
      //   subTitle: '请填写模式名称',
      //   confirmText: '确认',
      //   onConfirm: (data, { close }) => {
      //     close();
      //   },
      // });
    }

  };

  topView() {
    return (
      <TopBar.Container
        backgroundColor={kColor.type === 'dark'?"#020202":"#f4f4f4"}
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action size={20} source={Res.fback} color="#4C4C4C" onPress={() => TYSdk.Navigator.pop()} />
        <TopBar.Content />
        <TopBar.Action
          source={Res.ftack}
          color="#4C4C4C"
          size={18}
          style={{marginTop:500}}
          onPress={() => {
            this.state.listItem ? this.editClick() : this.addClick()
          }}
        />
      </TopBar.Container>
    );
  }

  onImputName(){
    const { customName } = this.state;


    Dialog.prompt({
      title: Strings.light_mode_name_title,
      cancelText: Strings.cancel,
      confirmText: Strings.ok,
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      value: customName,
      // defaultValue: this.state.customName || '',
      placeholder: Strings.light_mode_name_placeholder,
      onChangeText: text => {
        // 使用value props 可令prompt成为受控组件，控制其输入框内容
        console.log('onChangeText',text);

        const regex1 = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;// 中英文和数字
        if (regex1.test(text)) {
          const pattern = /[\u4e00-\u9fa5]/; // 匹配中文字符的正则表达式
          const regex = new RegExp(pattern, 'g');
          let count = 0;

          // 计算字符串中中文字符的数量
          let match;
          while ((match = regex.exec(text))) {
            count += match[0].length;
          }

          // 计算UTF-8编码下的字节长度
          const byteLength = encodeURI(text).split(/%..|./).length - 1 - count;

          // 如果字节长度超过8，则不设置状态，保持原来的文本
          if (byteLength <= 8) {
            this.setState({ customName: text });
            return text;
          }
        } else if (text === ''){
          this.setState({ customName: text });
          return text;
        }

      },
      onConfirm: (text, { close }) => {
        console.log('controlled text :', text);
        //setState({ promptControlled: text });
        this.setState({ customName: text });

        close();
      },
    });
  }

  toastView(tips, show){
    return(
      <Toast show={show} text={tips} onFinish={() => {
        this.setState( {showToast: false });
      }} />
    );
  }

  render() {
    const { light_edit_bright } = this.props;
    const { showToast, toastTips } = this.state;
    const titleColor = kColor.type === 'dark' ? "#fff":'#000000';
    return (

      <View style={[styles.container, kColor.theme[kColor.type].pageBgColor]}>
        { light_edit_bright ? this.topView() : null }

        {/* 新建或编辑 */}
        <View style={{ height: 100, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
          <Text style={[ kColor.theme[kColor.type].pageTitleColor,{ marginStart: 27, fontSize: 30}]}>{this.state.listItem ? Strings.page_title_edit : Strings.page_title_create_mode}</Text>
          {/* <TouchableOpacity
            style={{ marginEnd: 5, marginTop: -1 }}
            onPress={() => {
              this.state.listItem ? this.editClick() : this.addClick()
            }}
          >
            <Image style={styles.tackIcon} source={Res.ftack} resizeMode="center" />
          </TouchableOpacity> */}
        </View>

        <TouchableOpacity
          style={styles.cell}
          onPress={() => {
            this.onImputName();
          }}
        >
          <Text style={[ kColor.theme[kColor.type].titleColor, {fontSize: 16, fontWeight: "bold"}]}>{Strings.light_mode_name_title}</Text>
          <View style={[{flexDirection: "row", alignItems: "center"}]}>
            <Text style={[ kColor.theme[kColor.type].titleColor, { marginLeft: 20 }]}>{this.state.customName?this.state.customName:Strings.light_mode_name_placeholder}</Text>
            <Image source={Res.enter} />
          </View>
        </TouchableOpacity>

        <View style={{  }}>
          {/*<Divider style={{ marginTop: 10, alignSelf: 'center' }} color="#E5E5E5" width={Dimensions.get('window').width-40} />*/}

          {/* 亮度 */}
          <View style={styles.lightview}>
            <Text style={[styles.topText,kColor.theme[kColor.type].titleColor]}>{Strings.light_brightness_title}| {this.state.lightSet}%</Text>
            <Slider.Horizontal
              maximumValue={100}
              minimumValue={1}
              stepValue={1}
              // thumbTouchSize={{ width: 40, height: 40 }}
              value={this.state.lightSet}
              type="parcel"
              style={{ marginTop: 10, marginBottom: 10, marginLeft: 30, marginRight: 20 }}
              theme={{
                width: 300,
                height: 26,
                trackHeight: 26,
                trackRadius: 13,
                thumbTintColor: '#ffffff',
                minimumTrackTintColor: '#22a8dc',
                maximumTrackTintColor: '#E5E5E5',
              }}
              trackStyle={{
                height: 26,
                borderRadius: 13,
              }}
              thumbStyle={{
                // 会覆盖上面 theme 的thumbSize和thumbRadius
                width: 20,
                height: 20,
                borderRadius: 10,
                shadowOffset: {// 去掉滑块阴影
                  width: 0,
                  height: 0,
                },
                shadowOpacity: 0,
                shadowRadius: 0,
                elevation: 0,
                justifyContent: 'center',
                alignItems: 'center',
              }}
              thumbTouchSize={{ width: 26, height: 26 }}// 控制使最大最小时外圈保持正圆状态
              renderMinimumTrack={() => (
                <View
                  style={{
                    height: 48,
                    borderRadius: 24,
                    // backgroundColor: '#ac4545',
                  }}>
                  {/*<Text style={{ marginLeft: 20, marginTop:15, color: '#fff', }}>1</Text>*/}
                </View>
              )}
              renderMaximumTrack={() => (
                <View
                  style={{
                    height: 48,
                    borderRadius: 24,
                    // backgroundColor: '#ac4545',
                  }}>
                  {/*<Text style={{ alignSelf:'flex-end', marginRight: 20, marginTop:5, color: '#747474', }}>100</Text>*/}
                </View>
              )}
              // onValueChange={value => {
              //   this.setValue(value);
              // }}
              onSlidingComplete={value => {
                this.setLight(value);
                this.sliderClicked(value);
                // console.log(value);
              }}
            />
          </View>
        </View>
        
        <View style={{ marginTop: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start'}}>
          <Text style={[styles.topText, kColor.theme[kColor.type].titleColor]}>{Strings.light_color_title}</Text>
          <View style={{ marginLeft:10, width: 20, height: 20, backgroundColor: this.state.color,marginTop:10 }} />
        </View>
        <View style={{
          height: 300,
          width: 400,
          marginTop: 400,
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
          position: 'absolute'
        }}
        >

          <HueSaturationPicker
            maxSaturation="100"
            value={{ hue: 0, saturation: 0 }}
            onChange={value => {
              const h = value['hue'];
              const s = value['saturation'];
              const v = this.state.lightSet;
              console.log(h);
              console.log(s);
              console.log(v);
              const rgb = hsvToRgb( h, s, v );
              console.log(rgb);
              const red = this.numberToHex2(rgb['r']);
              const green = this.numberToHex2(rgb['g']);
              const blue = this.numberToHex2(rgb['b']);
              const rgbHex = red + green + blue;
              const rgbDec = this.hexToDec(rgbHex);
              this.sliderColor(rgbDec);
              this.setState({ modeRGB: rgbDec.toString() });
              let colorHexString = parseInt(rgbDec, 10).toString(16);// 10进制字符串转16进制字符串
              // 字符串前面补0，6是目标长度
              colorHexString = '#'+ colorHexString.padStart(6, '0');
              this.setState({ color: colorHexString});
            }}
          />
        </View>


        { showToast ? this.toastView(toastTips, showToast) : null }

      </View>
    );
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor: '#ffffff',
    height: 500,
  },
  topText: {
    marginTop: 20,
    marginStart: 27,
    height: 30,
    fontSize: 16,
    color: '#000',
  },
  tackIcon: {
    width: 60,
    height: 60,
  },
  cellTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "#000"
  },
  lightview: {
    // backgroundColor: "#ffffff",
    //marginTop: 20,
    height: 80,
    width: Dimensions.get("window").width - 20
  },
  cell: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    // backgroundColor: "#fff",
    height: 60,
    marginStart: 27,
    marginEnd: 10,
    marginTop: 10,
    // width: '100%',
    borderRadius: 12
  },
});

export default connect(({ dpState }) => ({
  dpState,
  light_edit_bright: dpState[light_edit_brightCode],
  light_edit_on: dpState[light_edit_onCode],
  light_edit_color: dpState[light_edit_colorCode],
  light_mode_list: dpState[light_mode_listCode],
}))(CustomLightScene);


